# -*- coding: utf-8 -*-
import os


def write_file(file_path, content):
    fo = open(file_path, "w")
    try:
        fo.write(content)
    finally:
        fo.close()
    return len(content)


def merge_all_files_content(files, split):
    merge_content = ''
    for f in files:
        fo = open(f, "r")
        try:
            merge_content += fo.read()
            merge_content += split
        finally:
            fo.close()
    return merge_content


def delete_file(file_path):
    if os.path.exists(file_path):
        os.remove(file_path)


def list_all_files(root_dir, choose_func, sort_key):
    result = []
    for f in os.listdir(root_dir):
        if choose_func(root_dir + f, f):
            result.append(root_dir + f)
    result.sort(key=sort_key)
    return result


def modify_file(file_path, key, replace):
    with open(file_path, "r") as f:
        lines = f.readlines()
    with open(file_path, "w") as f_w:
        for line in lines:
            if key in line:
                line = line.replace(key, replace)
            f_w.write(line)
